<?php

class TaskManager {
	
	private $taskService;
	
	public function __construct() {
		$this->taskService = TaskService::getInstance();
	}
	
	/**
	 * Run all tasks in the order
	 * 
	 */
	public function scheduleTasks($baseDate) {
		
		Yii::log('begin schedule tasks', CLogger::LEVEL_INFO, SCHEDULER_LOG);
		$waitingTasks = $this->getWaitingTasks();
		Yii::log('process waiting tasks, total: '. count($waitingTasks), CLogger::LEVEL_INFO, SCHEDULER_LOG);
		
		// Select run resource for it
		foreach ($waitingTasks as $oneTask) {
			$oneTask->selectExecutor();
		}		
		unset($waitingTasks);
		Yii::log('schedule tasks successfully', CLogger::LEVEL_INFO, SCHEDULER_LOG);
	}
	
	private function getWaitingTasks() {	
		$tasks =  $this->taskService->getWaitingTasks();
		return $this->createTaskInstances($tasks);
	}
	
	private function createTaskInstances($tasks) {
		
		$taskInstances = array();
		if(!is_array($tasks)) {
			return $taskInstances;
		}
		
		foreach ($tasks as $task) {	
			$taskInstances[] = new BaseTask($task);	
		}
		return $taskInstances;
	}
}
